﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Ruminate.Utils {

    public class FrameRateCounter : DrawableGameComponent {

        public SpriteFont SpriteFont { get; set; }

        readonly ContentManager _content;
        SpriteBatch _spriteBatch;
               
        int _frameRate, _frameCounter;
        TimeSpan _elapsedTime = TimeSpan.Zero;


        public FrameRateCounter(Game game) : base(game) {

            _content = new ContentManager(game.Services);
        }

        protected override void LoadContent() {

            _spriteBatch = new SpriteBatch(GraphicsDevice);          
        }


        protected override void UnloadContent() {

            _content.Unload();
        }


        public override void Update(GameTime gameTime) {

            _elapsedTime += gameTime.ElapsedGameTime;

            if (_elapsedTime <= TimeSpan.FromSeconds(1)) { return; }

            _elapsedTime -= TimeSpan.FromSeconds(1);
            _frameRate = _frameCounter;
            _frameCounter = 0;
        }


        public override void Draw(GameTime gameTime) {

            _frameCounter++;

            var fps = string.Format("fps: {0}", _frameRate);

            _spriteBatch.Begin();

            _spriteBatch.DrawString(SpriteFont, fps, new Vector2(GraphicsDevice.Viewport.Width - 109, 13), Color.LightGray);            
            _spriteBatch.DrawString(SpriteFont, fps, new Vector2(GraphicsDevice.Viewport.Width - 110, 12), Color.Black);            

            _spriteBatch.End();
        }
    }
}
